package top.songxs.gmall.product.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import top.songxs.gmall.common.constant.GmallCacheConstant;
import top.songxs.gmall.common.result.Result;
import top.songxs.gmall.product.rpc.biz.SkuInfoFeignRpcService;
import top.songxs.gmall.product.service.BloomFilterService;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class BloomFilterServiceImpl implements BloomFilterService {
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SkuInfoFeignRpcService skuInfoFeignRpcService;
    public static RBloomFilter<Long> bloomFilter;


    @PostConstruct
    public void initBloom() {
        bloomFilter = redissonClient.getBloomFilter(GmallCacheConstant.REDIS_SKU_INFO_BLOOM_FILTER);
        if (!bloomFilter.isExists()) {
            bloomFilter.tryInit(10000L, 0.000001);
            Result<List<Long>> result = skuInfoFeignRpcService.getAllSkuId();
            List<Long> ids = result.getData();
            ids.stream().forEach(bloomFilter::add);
        }
    }

    @Override
    public void resetBloomFilter() {
        String script = "redis.call('del',KEYS[1])\n" +
                "redis.call('del','{'.. KEYS[1]..'}:config')\n" +
                "redis.call('rename',KEYS[2],KEYS[1])\n" +
                "redis.call('rename','{'.. KEYS[2]..'}:config','{'.. KEYS[1]..'}:config')\n" +
                "return 1";
        RBloomFilter<Long> newFilter = redissonClient.getBloomFilter(GmallCacheConstant.REDIS_SKU_INFO_BLOOM_FILTER_NEW);
        if (!newFilter.isExists()) {
            newFilter.tryInit(10000L, 0.000001);
            Result<List<Long>> result = skuInfoFeignRpcService.getAllSkuId();
            List<Long> ids = result.getData();
            ids.stream().forEach(newFilter::add);
        }

        Long result = redisTemplate.execute(new DefaultRedisScript<>
                (script, Long.class), Arrays.asList(GmallCacheConstant.REDIS_SKU_INFO_BLOOM_FILTER, GmallCacheConstant.REDIS_SKU_INFO_BLOOM_FILTER_NEW));
        if (result == 1) {
            log.info("重置布隆过滤器成功！");
        }
    }
}
